package cn.jolyoulu.common.core.utils.io;


import lombok.extern.slf4j.Slf4j;

/**
 * @Author: JolyouLu
 * @Date: 2021/6/2 9:20
 * @Version 1.0
 */
@Slf4j
public class HexUtils {

    private static char[] DIGITS_LOWER = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e',
            'f'};
    private static char[] DIGITS_UPPER = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E',
            'F'};

    /**
     * byte字节转16进制字符串
     *
     * @param bData byte
     * @return string
     */
    public static String byte2Hex(byte bData) {
        char[] str = new char[2];
        str[0] = DIGITS_UPPER[(bData >> 4) & 0x0f];
        str[1] = DIGITS_UPPER[(bData >> 0) & 0x0f];
        return new String(str);
    }

    /**
     * byte数组转16进制字符串
     *
     * @param bData
     * @return
     */
    public static String byteArray2Hex(byte[] bData) {
        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < bData.length; i++) {
            builder.append(byte2Hex(bData[i]));
        }
        return builder.toString();
    }

    /**
     * 16进制字符串，转换为Byte
     *
     * @param hex 16进制字符串
     * @return byte
     */
    public static byte hex2Byte(String hex) {
        int intValue = Integer.parseInt(hex, 16);
        return (byte) intValue;
    }

    /**
     * 多个16进制字符串，转换为Byte数值
     *
     * @param hexString 16进制字符串
     * @return byte[]
     */
    public static byte[] hexString2byteArray(String hexString) {
        int hexLen = hexString.length();
        byte[] res = new byte[(hexLen / 2)];
        int j = 0;
        for (int i = 0; i < hexLen; i += 2) {
            res[j++] = hex2Byte(hexString.substring(i, i + 2));
        }
        return res;
    }

    /**
     * 打印16进制内容
     *
     * @param bData byte[]
     */
    public static void printHex(byte[] bData) {
        StringBuilder buffer = new StringBuilder();
        for (int i = 0; i < bData.length; i++) {
            buffer.append(byte2Hex(bData[i])).append(" ");
        }
        log.info(buffer.toString());
    }
}
